package com.ivanceras.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.ivanceras.client.SimulationService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


/**
 * The server side implementation of the RPC service.
 */

@SuppressWarnings("serial")
public class SimulationServiceImpl extends RemoteServiceServlet implements
		SimulationService {
	/**
	 * retrieve all the questions from the specified questionnaire ID
	 */
	public List<com.ivanceras.client.Question> getQuestions(long questionnaireKey){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Questionnaire qnaire = pm.getObjectById(Questionnaire.class, questionnaireKey);
	    //qnaire.getQuestions();
		List<com.ivanceras.client.Question> questionList = new ArrayList<com.ivanceras.client.Question>();
		List<com.ivanceras.server.Question> sqList= qnaire.getQuestions();
		System.out.println("sqList.size(): "+sqList.size());
		int size = sqList.size();
		for(Question sqn: sqList){
			questionList.add(server2clientQuestion(sqn));
		}
		pm.close();
		return questionList;
	}
	/**
	 * Retrieve all questionnaire (info only) from the datastore
	 */
	public ArrayList<com.ivanceras.client.Questionnaire> getQuestionnaires(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		System.out.println("Getting questionnaires....");
		ArrayList<com.ivanceras.client.Questionnaire> qnnaireList = new ArrayList<com.ivanceras.client.Questionnaire>();
		 
		Query query = pm.newQuery(Questionnaire.class);
		try{
			List<Questionnaire> results = (List<Questionnaire>)query.execute();
	        if (results.iterator().hasNext()) {
	            for (Questionnaire qnaire : results) {
	            	com.ivanceras.client.Questionnaire clientQnr= new com.ivanceras.client.Questionnaire();
	                clientQnr.title = qnaire.title;
	                clientQnr.description = qnaire.description;
	                clientQnr.questionnaireID = qnaire.questionnaireID;
	                clientQnr.items = qnaire.getItems();
	                System.out.println("items: "+clientQnr.items);
	                qnnaireList.add(clientQnr);
	            }
	        } else {
	            System.out.println("No questionnaires.. create a new one!");
	        }
		}finally{
			pm.close();
		}
		 return qnnaireList;
	}
	/**
	 * Used when adding a question to an existing questionnaire
	 */
	@Override
	public com.ivanceras.client.Question addNewQuestion(long questionnaireKey, String questionText , ArrayList<com.ivanceras.client.Choice> choices){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Questionnaire qnaire = pm.getObjectById(Questionnaire.class, questionnaireKey);
	    qnaire.getQuestions();//retrieve before adding so as the child objects are fetch
	    Question question = new Question(questionText);
	    for(com.ivanceras.client.Choice cch:choices){
		    question.addChoice(cch.text,cch.isCorrect);
	    }
	    qnaire.addQuestion(question);
		pm.makePersistent(qnaire);
		pm.close();
		return server2clientQuestion(question);
	}
	/**
	 * Implementation for questionnaire creation
	 */
	public com.ivanceras.client.Questionnaire createQuestionnaire(String title, String description){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Questionnaire qnaire = new Questionnaire(title, description);
		Questionnaire sqnr = pm.makePersistent(qnaire);
		pm.close();
		//have to copy server model to client mode, find a way to unify this one in the future
		com.ivanceras.client.Questionnaire cqnr = new com.ivanceras.client.Questionnaire();
		cqnr.title = sqnr.title;
		cqnr.description = sqnr.description;
		cqnr.questionnaireID = sqnr.questionnaireID;
		cqnr.items = sqnr.questions.size();
		return cqnr;
	}
	/**
	 * used when a questionnaire infor is edited
	 */
	public com.ivanceras.client.Questionnaire saveQuestionnaire(long questionnaireKey, String title, String description){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Questionnaire qnaire = pm.getObjectById(Questionnaire.class, questionnaireKey);
	    System.out.println("Orig qnaire: "+qnaire.questionnaireID);
	    System.out.println("orig title: "+qnaire.title);
	    System.out.println("orig desc: "+qnaire.description);

	    //qnaire.getQuestions();
	    if(qnaire.title != title){
	    	qnaire.setTitle(title); //questionnaire is not updated by just merely setting the public properties
	    }
	    if(qnaire.description != description){
	    	qnaire.setDescription(description);
	    }

	    System.out.println("Saving Qnr ID: "+qnaire.questionnaireID);
	    System.out.println("title: "+qnaire.title);
	    System.out.println("desc: "+qnaire.description);
    	
    	pm.makePersistent(qnaire);
	    pm.close();
	    com.ivanceras.client.Questionnaire cqnr = new com.ivanceras.client.Questionnaire();
	    cqnr.title = qnaire.title;
	    cqnr.description = qnaire.description;
	    cqnr.questionnaireID = qnaire.questionnaireID;
		return cqnr;
	}
	/**
	 * used in editing a certain question in a questionnaire
	 * @param questionId
	 * @param questionText
	 * @param choices
	 * @return
	 */
	public com.ivanceras.client.Question saveQuestion(com.ivanceras.client.Question question){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Questionnaire qnaire = pm.getObjectById(Questionnaire.class, question.questionnaireID);
    	System.out.println("editedquestionIDs:"+question.questionId);
	    for(Question sqn: qnaire.getQuestions()){
	    	System.out.println("questionIDs:"+sqn.questionnaireID);
	    	if(sqn.questionnaireID == question.questionId){
	    		Question newQn = new Question(question.text);
			    for(com.ivanceras.client.Choice cch : question.choiceList){
				    newQn.addChoice(cch.text, cch.isCorrect);
			    }
			    qnaire.saveQuestion(sqn, newQn);
			    pm.close();
			    System.out.println("Question saved!");
			    return new com.ivanceras.client.Question();
	    	}
	    }
	    return null;
	}
	/*
	public com.ivanceras.client.Question saveQuestion(com.ivanceras.client.Question question){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Questionnaire qnaire = pm.getObjectById(Questionnaire.class, question.questionnaireKey);
    	System.out.println("editedquestionIDs:"+question.questionId);
	    for(Question sqn: qnaire.getQuestions()){
	    	System.out.println("questionIDs:"+sqn.key.getId());
	    	if(sqn.key.getId() == question.questionId){
	    		if(qnaire.questions.remove(sqn)){
	    			System.out.println("Remove 1 question...left: "+qnaire.questions.size());
	    		}
	    		Question newQn = new Question(question.text);
			    for(com.ivanceras.client.Choice cch : question.choiceList){
				    newQn.addChoice(cch.text, cch.isCorrect);
			    }
			    qnaire.addQuestion(newQn);
			    pm.close();
				return server2clientQuestion(newQn);
	    	}
	    }
	    return null;
	}*/
	/**
	 * convert server question object into client question object for serialization
	 * @param sqn
	 * @return
	 */
	public com.ivanceras.client.Question server2clientQuestion(Question sqn){
		com.ivanceras.client.Question cqn = new com.ivanceras.client.Question();
		cqn.text = sqn.text;
		cqn.questionId = sqn.questionnaireID;
		cqn.questionnaireID = sqn.questionnaireID;
		for(Choice qc : sqn.getChoices()){
			cqn.addChoice(qc.getText(),qc.isCorrect);
		}
		return cqn;
	}
}
